{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#导入包\n",
    "from sklearn.feature_extraction import DictVectorizer\n",
    "from sklearn import tree\n",
    "from sklearn import preprocessing\n",
    "import csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#读入数据\n",
    "Dtree = open('AllElectronics.csv','r')\n",
    "reader = csv.reader(Dtree)\n",
    "\n",
    "#获取第一行数据\n",
    "headers = reader.__next__()\n",
    "#print(headers)\n",
    "\n",
    "#定义两个列表\n",
    "featureList = []\n",
    "labelList = []\n",
    "\n",
    "for row in reader:\n",
    "    #把label存入list\n",
    "    labelList.append(row[-1])\n",
    "    rowDict = {}\n",
    "    for i in range(1,len(row)-1):\n",
    "        rowDict[headers[i]] = row[i] #建立一个数据字典          \n",
    "    featureList.append(rowDict) #把数据字典存入list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x_data:[[ 0.  0.  1.  0.  1.  1.  0.  0.  1.  0.]\n",
      " [ 0.  0.  1.  1.  0.  1.  0.  0.  1.  0.]\n",
      " [ 1.  0.  0.  0.  1.  1.  0.  0.  1.  0.]\n",
      " [ 0.  1.  0.  0.  1.  0.  0.  1.  1.  0.]\n",
      " [ 0.  1.  0.  0.  1.  0.  1.  0.  0.  1.]\n",
      " [ 0.  1.  0.  1.  0.  0.  1.  0.  0.  1.]\n",
      " [ 1.  0.  0.  1.  0.  0.  1.  0.  0.  1.]\n",
      " [ 0.  0.  1.  0.  1.  0.  0.  1.  1.  0.]\n",
      " [ 0.  0.  1.  0.  1.  0.  1.  0.  0.  1.]\n",
      " [ 0.  1.  0.  0.  1.  0.  0.  1.  0.  1.]\n",
      " [ 0.  0.  1.  1.  0.  0.  0.  1.  0.  1.]\n",
      " [ 1.  0.  0.  1.  0.  0.  0.  1.  1.  0.]\n",
      " [ 1.  0.  0.  0.  1.  1.  0.  0.  0.  1.]\n",
      " [ 0.  1.  0.  1.  0.  0.  0.  1.  1.  0.]]\n",
      "['age=middle_aged', 'age=senior', 'age=youth', 'credit_rating=excellent', 'credit_rating=fair', 'income=high', 'income=low', 'income=medium', 'student=no', 'student=yes']\n",
      "labelList:['no', 'no', 'yes', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'yes', 'yes', 'yes', 'yes', 'no']\n",
      "y_data:[[0]\n",
      " [0]\n",
      " [1]\n",
      " [1]\n",
      " [1]\n",
      " [0]\n",
      " [1]\n",
      " [0]\n",
      " [1]\n",
      " [1]\n",
      " [1]\n",
      " [1]\n",
      " [1]\n",
      " [0]]\n"
     ]
    }
   ],
   "source": [
    "#把数据转换成0-1表示\n",
    "vec = DictVectorizer()\n",
    "x_data = vec.fit_transform(featureList).toarray()\n",
    "print(\"x_data:\"+str(x_data))\n",
    "\n",
    "#打印属性名称\n",
    "print(vec.get_feature_names())\n",
    "print(\"labelList:\"+str(labelList))\n",
    "\n",
    "#把标签转换成0-1表示\n",
    "lb = preprocessing.LabelBinarizer()\n",
    "y_data = lb.fit_transform(labelList)\n",
    "print(\"y_data:\"+str(y_data))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=None,\n",
       "            max_features=None, max_leaf_nodes=None,\n",
       "            min_impurity_decrease=0.0, min_impurity_split=None,\n",
       "            min_samples_leaf=1, min_samples_split=2,\n",
       "            min_weight_fraction_leaf=0.0, presort=False, random_state=None,\n",
       "            splitter='best')"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#创建决策树模型\n",
    "model = tree.DecisionTreeClassifier(criterion ='entropy')\n",
    "#输入数据建立模型\n",
    "model.fit(x_data,y_data)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x_test:[ 1.  0.  0.  0.  1.  1.  0.  0.  1.  0.]\n",
      "predict:[1]\n"
     ]
    }
   ],
   "source": [
    "#测试\n",
    "x_test =x_data[2]\n",
    "print(\"x_test:\"+str(x_test))\n",
    "predict =model.predict(x_test.reshape(1,-1))\n",
    "print(\"predict:\"+str(predict))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (backend.py, line 107)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"D:\\Anaconda\\lib\\site-packages\\graphviz\\backend.py\"\u001b[1;36m, line \u001b[1;32m107\u001b[0m\n\u001b[1;33m    return f'{s} [stderr: {self.stderr!r}]'\u001b[0m\n\u001b[1;37m                                          ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "import graphviz\n",
    "\n",
    "dot_data = tree.export_graphviz(model,\n",
    "                               out_file = None,\n",
    "                               feature_names = vec.get_feature_names,\n",
    "                               class_names = lb.classes_,\n",
    "                               filled = True,\n",
    "                               rounded = True,\n",
    "                               special_character = True)\n",
    "graph = graphviz.Source(dot_data)\n",
    "graph.render('computer')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [Root]",
   "language": "python",
   "name": "Python [Root]"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
